from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import User, InviteCode

class UserRegisterForm(UserCreationForm):
    phone_number = forms.CharField(
        label='手机号',
        max_length=11,
        help_text=None
    )
    nickname = forms.CharField(
        label='昵称',
        max_length=15,
        required=True,
        help_text=None
    )
    invite_code = forms.CharField(
        label='邀请码',
        max_length=6,
        required=True,
        help_text=None,
        widget=forms.HiddenInput()
    )
    
    class Meta:
        model = User
        fields = ['phone_number', 'nickname', 'password1', 'password2', 'invite_code']
        help_texts = {
            'password1': None,
            'password2': None,
        }
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.help_text = None
    
    def clean_phone_number(self):
        phone_number = self.cleaned_data.get('phone_number')
        if User.objects.filter(phone_number=phone_number).exists():
            raise forms.ValidationError('该手机号已被注册')
        return phone_number
    
    def clean_invite_code(self):
        code = self.cleaned_data.get('invite_code')
        try:
            invite = InviteCode.objects.get(code=code, used_by__isnull=True)
            return invite
        except InviteCode.DoesNotExist:
            raise forms.ValidationError('无效的邀请码')
    
    def save(self, commit=True):
        user = super().save(commit=False)
        # 自动设置用户名为 pn_ + 手机号
        user.username = f"pn_{self.cleaned_data['phone_number']}"
        user.nickname = self.cleaned_data['nickname']
        user.phone_number = self.cleaned_data['phone_number']
        
        if commit:
            user.save()
        return user